package com.zhkc.wisdom.common.feign.config;

import com.zhkc.wisdom.common.configure.constant.ConfigureConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

/**
 * @Description feign拦截器，用于feign调用向下传递token及用户信息
 * @User zzw
 * @Date 12:12 2023/11/15
 * @company zhkc
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = ConfigureConstant.ZHKC_PROPERTIES_PREFIX
        + ".feign", name = "enabled", havingValue = "true", matchIfMissing = false)
public class FeignClientInterceptorConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        log.info("【FeignClientInterceptor】拦截器执行了,将Headers信息传递给下游服务");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != attributes) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    template.header(name, values);
                }
            }
        }
    }
}